# Canvas = require('canvas')
Canvas = {}
resErr = require('./util').resErr

# 生成ipo使用的验证码
exports.captcha = (req, res) ->

  params = {}
  #params.color = 'rgb(0,100,100)'
  #params.background = 'rgb(255,200,150)'
  params.color = '#4c8eba'
  params.background = '#d2ccc1'

  g_width = 190
  g_height = 120

  canvas = new Canvas(g_width,g_height)
  ctx = canvas.getContext('2d');
  ctx.antialias = 'gray';
  ctx.fillStyle = params.background;
  ctx.fillRect(0, 0, g_width, g_height)
  ctx.fillStyle = params.color
  ctx.lineWidth = 8
  ctx.strokeStyle = params.color
  ctx.font = '95px sans'

  for i in [0..1]
    ctx.strokeStyle = '#9cd7f4'
    ctx.lineWidth = 2
    ctx.moveTo(20, Math.random() * 10)
    ctx.bezierCurveTo(80, Math.random() * 200, 80, Math.random() * 200, 115, Math.random() * 200)
    ctx.stroke()

  ctx.lineWidth = 4

  text = ('' + Math.random()).substr(3, 4)

  for i in [0..text.length-1]
    ctx.setTransform(Math.random() * 0.15 + 1, Math.random() * 0.15, Math.random() * 0.15, Math.random() * 0.15 + 1, 36 * i + 20, 100)
    ctx.fillText(text.charAt(i), 0, 0)

  canvas.toBuffer (err, buf) ->
    if(req.session)
      req.session.captcha = text
    res.end(buf);


# 检验验证码
exports.check_captcha = (req, res, next) ->
  captcha = req.session?.captcha
  req.session?.captcha  = ''
  if captcha && req.param('captcha') && captcha == req.param('captcha')
    return next()
  return resErr res,'验证码错误'